<template>
  <a-form-item :label="label" :validate-status="validateStatus" :help="helpMessage">
    <div class="button-group">
      <a-button
        size="small"
        v-for="(option, index) in options"
        :key="index"
        :type="isSelected(option.value) ? 'primary' : 'default'"
        @click="toggleSelection(option)"
      >
        {{ option.label }}
      </a-button>
    </div>
  </a-form-item>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
  label: {
    type: String,
    default: '',
  },
  options: {
    type: Array,
    required: true,
  },
  value: {
    type: [String, Array],
    default: () => [],
  },
  mode: {
    type: String,
    validator: (value) => ['single', 'multiple'].includes(value),
    default: 'single',
  },
});

const emit = defineEmits(['update:value', 'change']);

const selectedValues = ref(props.value);
const validateStatus = ref('');
const helpMessage = ref('');

const isSelected = (value) => {
  if (props.mode === 'single') {
    return selectedValues.value === value;
  }
  return selectedValues.value.includes(value);
};

const toggleSelection = (option) => {
  if (props.mode === 'single') {
    selectedValues.value = option.value;
  } else {
    const index = selectedValues.value.indexOf(option.value);
    if (index > -1) {
      selectedValues.value.splice(index, 1);
    } else {
      selectedValues.value.push(option.value);
    }
  }
  emit('update:value', selectedValues.value);
  emit('change', selectedValues.value);
};

watch(
  () => selectedValues.value,
  (newVal) => {
    emit('update:value', newVal);
  },
  { deep: true }
);

watch(
  () => props.value,
  (newVal) => {
    selectedValues.value = newVal;
  },
  { deep: true, immediate: true }
);
</script>

<style scoped>
.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 这个值可以根据你的设计需求调整 */
}
</style>